from custom.handlers.basehandler import BaseRequestHandler
from settings.config import config
import os
import uuid
import time


class UploadHandler(BaseRequestHandler):
    def get(self, *args, **kwargs):
        self.redirect404()

    def post(self):
        try:
            files = self.request.files['file']
        except KeyError as exp:
            files = []
        if len(files) == 0:
            self.success(-1, u'没有文件', None)
            return
        uploads_url = []
        try:
            for file in files:
                uploads_url.append(self.save_file(file))
            self.success(200, '', {'urls': uploads_url})
        except Exception as e:
            print('e', e)
            self.success(-2, u'系统错误', None)

    @staticmethod
    def get_current_date():
        time_tuple = time.localtime(time.time())
        str1 = str(time_tuple[0])
        str2 = str(time_tuple[1])
        str3 = str(time_tuple[2])
        if time_tuple[1] < 10:
            str2 = '0' + str(time_tuple[1])
        if time_tuple[2] < 10:
            str3 = '0' + str(time_tuple[2])
        return str1 + str2 + str3

    @staticmethod
    def get_ext(file):
        file_name = file['filename']
        return file_name.split('.')[-1].lower()

    def set_middle_path(self):
        now_data = self.get_current_date()
        middle_path = config.upload_path + '/' + now_data
        if not os.path.exists(os.path.join(config.APP_ROOT, middle_path)):
            os.mkdir(os.path.join(config.APP_ROOT, middle_path))
        return middle_path

    def save_file(self, file):
        print()
        file_name = str(uuid.uuid4()) + '.' + self.get_ext(file)
        app_upload_path = os.path.join(self.set_middle_path(), file_name)
        real_path = os.path.join(config.APP_ROOT, app_upload_path)
        upload_file = open(real_path, "wb+")
        upload_file.write(file["body"])
        upload_file.close()
        return '/' + app_upload_path

